package com.qianhui.dao;

import com.qianhui.common.CM;
import com.qianhui.common.IResult;
import com.qianhui.pojo.Article;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Transaction;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

/**
 * A data access object (DAO) providing persistence and search support for
 * Article entities. Transaction control of the save(), update() and delete()
 * operations can directly support Spring container-managed transactions or they
 * can be augmented to handle user-managed Spring transactions. Each of these
 * methods provides additional information for how to configure it for the
 * desired type of transaction control.
 *
 * @author MyEclipse Persistence Tools
 * @see com.qianhui.pojo.Article
 */
public class ArticleDAO extends BaseHibernateDAO
{
    private static final Logger log = LoggerFactory.getLogger(ArticleDAO.class);
    // property constants
    public static final String ARTICLE_NAME = "articleName";
    public static final String ARTICLE_TIPS = "articleTips";
    public static final String ARTICLE_DETAIL = "articleDetail";
    public static final String USER_ID = "userId";

    public Article save(Article transientInstance)
    {
        Transaction tx = null;
        try
        {
            tx = getSession().beginTransaction();
            getSession().saveOrUpdate(transientInstance);
            tx.commit();
        } catch (HibernateException e)
        {
            e.printStackTrace();
            if (tx != null)
            {
                tx.rollback();
            }
            return null;
        } finally
        {
            if (getSession() != null && getSession().isOpen() == true)
            {
                getSession().close();
            }
        }
        return transientInstance;
    }

    public List<Article> saveList(List<Article> list)
    {
        Transaction tx = null;
        try
        {
            tx = getSession().beginTransaction();
            for (Article temp : list)
            {
                getSession().saveOrUpdate(temp);
            }
            tx.commit();
        } catch (HibernateException e)
        {
            e.printStackTrace();
            if (tx != null)
            {
                tx.rollback();
            }
            return null;
        } finally
        {
            if (getSession() != null && getSession().isOpen() == true)
            {
                getSession().close();
            }
        }
        return list;
    }

    public int delete(Article persistentInstance)
    {
        Transaction tx = null;
        try
        {
            tx = getSession().beginTransaction();
            getSession().delete(persistentInstance);
            tx.commit();
        } catch (HibernateException e)
        {
            e.printStackTrace();
            if (tx != null)
            {
                tx.rollback();
            }
            return IResult.DELETE_EXCEPTION;
        } finally
        {
            if (getSession() != null && getSession().isOpen() == true)
            {
                getSession().close();
            }
        }
        return IResult.DELETE_SUCCESS;
    }

    public Article findById(java.lang.String id)
    {
        log.debug("getting Article instance with id: " + id);
        try
        {
            Article instance = (Article) getSession().get("com.qianhui.pojo.Article", id);
            return instance;
        } catch (HibernateException e)
        {
            e.printStackTrace();
            return null;
        } finally
        {
            if (getSession() != null && getSession().isOpen() == true)
            {
                getSession().close();
            }
        }
    }

    public List findByProperty(String propertyName, Object value)
    {
        log.debug("finding Article instance with property: " + propertyName + ", value: " + value);
        try
        {
            String queryString = "from Article as model where model." + propertyName + "= ?";
            Query queryObject = getSession().createQuery(queryString);
            queryObject.setParameter(0, value);
            return queryObject.list();
        } catch (HibernateException e)
        {
            e.printStackTrace();
            return null;
        } finally
        {
            if (getSession() != null && getSession().isOpen() == true)
            {
                getSession().close();
            }
        }
    }

    public List findByArticleName(Object articleName)
    {
        return findByProperty(ARTICLE_NAME, articleName);
    }

    public List findByArticleTips(Object articleTips)
    {
        return findByProperty(ARTICLE_TIPS, articleTips);
    }

    public List findByArticleDetail(Object articleDetail)
    {
        return findByProperty(ARTICLE_DETAIL, articleDetail);
    }

    public List findByUserId(Object userId)
    {
        return findByProperty(USER_ID, userId);
    }

    public List findAll()
    {
        log.debug("finding all Article instances");
        try
        {
            String queryString = "from Article";
            Query queryObject = getSession().createQuery(queryString);
            return queryObject.list();
        } catch (HibernateException e)
        {
            e.printStackTrace();
            return null;
        } finally
        {
            if (getSession() != null && getSession().isOpen() == true)
            {
                getSession().close();
            }
        }
    }


    public List getListByIndexAndPageSizeAnd_keyword(int index, int pageSize, String keyword)
    {
        try
        {
            String sql = "from Article a :kSql order by a.articleUpdateTime desc";
            if (CM.validIsEmptyWithTrim(keyword) == true)
            {
                sql = sql.replace(":kSql", " ");
            }
            else
            {
                sql = sql.replace(":kSql", "where (a.articleId like :keyword or a.articleName like :keyword or a.articleTips like :keyword)");
            }
            Query query = getSession().createQuery(sql);

            if (CM.validIsEmptyWithTrim(keyword) == false)
            {
                query.setParameter("keyword", "%" + keyword + "%");
            }
            query.setFirstResult((index - 1) * pageSize);
            query.setMaxResults(pageSize);
            List tempList = query.list();
            if (tempList == null)
            {
                return null;
            }
            else
            {
                if (tempList.size() > 0)
                {
                    return tempList;
                }
                else
                {
                    return null;
                }
            }
        } catch (HibernateException e)
        {
            e.printStackTrace();
            return null;
        } finally
        {
            if (getSession() != null && getSession().isOpen() == true)
            {
                getSession().close();
            }
        }
    }

    public int getTotalCountBy_keyword(String keyword)
    {
        try
        {
            String sql = "select count(*) from Article a :kSql order by a.articleUpdateTime desc";
            if (CM.validIsEmptyWithTrim(keyword) == true)
            {
                sql = sql.replace(":kSql", " ");
            }
            else
            {
                sql = sql.replace(":kSql", "where (a.articleId like :keyword or a.articleName like :keyword or a.articleTips like :keyword)");
            }
            Query query = getSession().createQuery(sql);

            if (CM.validIsEmptyWithTrim(keyword) == false)
            {
                query.setParameter("keyword", "%" + keyword + "%");
            }
            int num = ((Number) query.iterate().next()).intValue();
            return num;
        } catch (HibernateException e)
        {
            e.printStackTrace();
            return -1;
        } finally
        {
            if (getSession() != null && getSession().isOpen() == true)
            {
                getSession().close();
            }
        }
    }

}